package com.xky.ui.module.productManagement;

import com.xky.pojo.*;
import com.xky.ui.module.customersManagement.CustomersInfo;
import com.xky.ui.module.customersManagement.select.SelectCustomers;
import com.xky.ui.module.inventorManagement.add.AddInvenTory;
import com.xky.ui.module.inventorManagement.InvenToryInfo;
import com.xky.ui.module.inventorManagement.select.SelectInvenTory;
import com.xky.ui.module.productManagement.add.AddProduct;
import com.xky.ui.module.productManagement.delete.DeleteProduct;
import com.xky.ui.module.productManagement.select.ProductService;
import com.xky.ui.module.productManagement.select.SelectCateGory;
import com.xky.ui.module.productManagement.select.SelectProduct;
import com.xky.ui.module.productManagement.update.UpdateProduct;
import com.xky.ui.module.salesManagement.SalesInfo;
import com.xky.ui.module.salesManagement.SalesShipmentsInfo;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;
import com.xky.ui.module.salesManagement.select.SelectSalesShipment;
import com.xky.ui.module.supplierManagement.SupplierInfo;
import com.xky.ui.module.supplierManagement.select.SelectSupplier;
import com.xky.ui.module.warehouseManagement.WarehouseInfo;
import com.xky.ui.module.warehouseManagement.select.WarehouseService;
import lombok.Getter;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;


public class BasicMassage {
    static JTable table;
    @Getter
    private static String description;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);//用于标题、主要按钮等突出显示元素
    private static final Color SECONDARY_COLOR = new Color(255, 255, 255);//用于背景色或次要面板
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);//用于普通按钮的默认状态
    private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);//用于面板间的分隔线
    private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);//用于搜索/查询类操作按钮

    /**
     * 创建首页面板
     * @return 首页面板
     */
    public static JPanel createHomePanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));//在每个区域之间添加水平和垂直方向上的间距，都是10个像素。
        //这行代码的目的是为 panel 设置一个边框。setBorder 方法用于指定一个边框对象，这个对象将围绕着面板进行绘制。
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setBackground(new Color(245, 245, 245));

        // 创建顶部欢迎面板
        JPanel welcomePanel = new JPanel(new BorderLayout());
        welcomePanel.setBackground(new Color(48, 57, 82));
        welcomePanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));

        JLabel titleLabel = new JLabel("商品库存管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 32));
        titleLabel.setForeground(Color.WHITE);
        welcomePanel.add(titleLabel, BorderLayout.NORTH);

        JLabel subtitleLabel = new JLabel("高效管理您的商品和库存");
        subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        subtitleLabel.setForeground(new Color(200, 200, 200));
        subtitleLabel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
        welcomePanel.add(subtitleLabel, BorderLayout.CENTER);

        panel.add(welcomePanel, BorderLayout.NORTH);

        // 创建中央信息面板
        JPanel infoPanel = new JPanel(new GridLayout(3, 2, 25, 25));//3, 2, 25, 25分别代表行，列，垂直间距，水平间距
        infoPanel.setBorder(BorderFactory.createEmptyBorder(35, 35, 35, 35));
        infoPanel.setBackground(new Color(245, 245, 245));

        // 添加统计卡片
        // 向信息面板添加多个仪表盘卡片，展示商品、分类、仓库、库存、供应商、客户、销售订单和销售发货的统计信息
infoPanel.add(createDashboardCard("商品总数", getProductCount(), "商品基础信息",
                new Color(41, 128, 185), new ImageIcon("lib/1.jpg")));

        infoPanel.add(createDashboardCard("分类总数", getCategoryCount(), "商品分类",
                new Color(39, 174, 96), new ImageIcon("lib/2.jpg")));

        infoPanel.add(createDashboardCard("仓库总数", getWarehouseCount(), "仓库信息",
                new Color(142, 68, 173), new ImageIcon("lib/3.jpg")));

        infoPanel.add(createDashboardCard("库存情况", getInventoryCount(), "库存记录",
                new Color(0, 211, 84), new ImageIcon("lib/4.jpg")));

        infoPanel.add(createDashboardCard("供应商总数", getSupplierCount(), "供应商信息",
                new Color(100, 199, 188), new ImageIcon("lib/5.jpg")));

        infoPanel.add(createDashboardCard("客户情况",getCustomerCount(),"客户信息",
                new Color(11, 245, 220),new ImageIcon("lib/6.jpg")));

        infoPanel.add(createDashboardCard("销售订单",getSalesOrderCount(),"销售订单信息",
                new Color(154, 20, 232),new ImageIcon("lib/7.jpg")));

        infoPanel.add(createDashboardCard("销售发货",getSalesShipmentCount(),"销售发货信息",
                new Color(196, 120, 50),new ImageIcon("lib/8.jpg")));
        panel.add(infoPanel, BorderLayout.CENTER);

        // 添加底部快捷功能面板
        JPanel quickPanel = new JPanel(new BorderLayout());
        quickPanel.setBackground(new Color(240, 240, 240));
        // 设置快速面板的边框，由一个复合边框组成，该复合边框包含一个顶部有1像素宽灰色边框和一个内部有20像素上下及35像素左右的空白边框
        quickPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(20, 35, 20, 35)
        ));


        JLabel quickTitle = new JLabel("快捷功能");
        quickTitle.setFont(new Font("微软雅黑", Font.BOLD, 18));
        quickTitle.setForeground(new Color(70, 70, 70));
        // 设置快速标题的边框，底部留有15像素的空白边距
        quickTitle.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0));

        quickPanel.add(quickTitle, BorderLayout.NORTH);

        JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonsPanel.setOpaque(false);

        // 添加快捷按钮
        JButton addProductBtn = createQuickButton("添加商品", new Color(41, 128, 185));
        addProductBtn.addActionListener(e -> handleAddButtonClick());
        buttonsPanel.add(addProductBtn);

        JButton queryProductBtn = createQuickButton("查询商品", new Color(39, 174, 96));
        queryProductBtn.addActionListener(e -> new SelectProduct());
        buttonsPanel.add(queryProductBtn);

        JButton addInventoryBtn = createQuickButton("添加库存", new Color(142, 68, 173));
        addInventoryBtn.addActionListener(e -> new AddInvenTory());
        buttonsPanel.add(addInventoryBtn);

        JButton manageWarehouseBtn = createQuickButton("管理仓库", new Color(211, 84, 0));
        manageWarehouseBtn.addActionListener(e -> WarehouseInfo.showWarehouseInfoPage());
        buttonsPanel.add(manageWarehouseBtn);

        JButton customerBtn = createQuickButton("客户管理", new Color(98, 32, 238));
        customerBtn.addActionListener(e -> CustomersInfo.showCustomersPage());
        buttonsPanel.add(customerBtn);

        JButton supplierBtn = createQuickButton("供应商管理", new Color(226, 200, 72));
        supplierBtn.addActionListener(e -> SupplierInfo.showSupplierInfoPage());
        buttonsPanel.add(supplierBtn);

        quickPanel.add(buttonsPanel, BorderLayout.CENTER);

        panel.add(quickPanel, BorderLayout.SOUTH);

        return panel;
    }




    /**
     * 创建快捷按钮
     */
    private static JButton createQuickButton(String text, Color color) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setForeground(Color.WHITE);
        button.setBackground(color);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button.setPreferredSize(new Dimension(150, 40));

        // 添加鼠标悬停效果
        Color darkerColor = color.darker();
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(darkerColor);
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(color);
            }
        });

        return button;
    }

    /**
     * 创建仪表盘卡片
     */
    private static JPanel createDashboardCard(String title, String value, String description, Color color, ImageIcon icon) {
        // 设置基本信息类的描述信息
        BasicMassage.description = description;
        // 创建一个新的JPanel，使用BorderLayout布局管理器，并设置水平和垂直间距
        JPanel card = new JPanel(new BorderLayout(10, 0));
        // 设置JPanel的背景颜色为白色
        card.setBackground(Color.WHITE);
        // 设置JPanel的边框，内侧为一个1像素宽的浅灰色实线边框，外侧为一个15像素的空边框以增加内边距
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));


        // 左侧图标区域
        JPanel leftStrip = new JPanel(new BorderLayout());
        leftStrip.setPreferredSize(new Dimension(80, 0));
        leftStrip.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

        if (icon != null && icon.getIconWidth() > 0) {
            try {

                // 创建一个自定义的JLabel，用于绘制缩放后的图标
                JLabel iconLabel = new JLabel() {
                    @Override
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        // 获取图片并缩放到面板大小
                        Image img = icon.getImage();

                       // 创建一个Graphics2D对象，并设置其渲染提示以提高图像质量和平滑度
                        Graphics2D g2d = (Graphics2D) g.create();
                        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);



                        // 在当前组件上绘制图像，图像的左上角位于(0,0)，宽度和高度调整为组件的宽度和高度
                        g2d.drawImage(img, 0, 0, getWidth(), getHeight(), this);

                        g2d.dispose();
                    }
                };

                iconLabel.setMinimumSize(new Dimension(80, 100));
                iconLabel.setPreferredSize(new Dimension(80, 100));

                leftStrip.add(iconLabel, BorderLayout.CENTER);
            } catch (Exception e) {
                System.err.println("图标加载失败: " + e.getMessage());
            }
        } else {
            leftStrip.setBackground(color);
        }


        card.add(leftStrip, BorderLayout.WEST);

        // 右侧内容
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setOpaque(false);
        contentPanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 5));

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        titleLabel.setForeground(new Color(100, 100, 100));
        titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(titleLabel);

        contentPanel.add(Box.createVerticalStrut(10));

        JLabel valueLabel = new JLabel(value);
        valueLabel.setFont(new Font("微软雅黑", Font.BOLD, 36));
        valueLabel.setForeground(color);
        valueLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(valueLabel);

        contentPanel.add(Box.createVerticalGlue());

        JPanel linkPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        linkPanel.setOpaque(false);
        linkPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        contentPanel.add(linkPanel);

        card.add(contentPanel, BorderLayout.CENTER);

        // 为整个卡片添加点击事件
        card.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 鼠标点击时导航到详情页
                navigateToDetailPage(description);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // 鼠标进入时设置卡片边框
                card.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(color, 1),
                        BorderFactory.createEmptyBorder(15, 15, 15, 15)
                ));
            }


            @Override
            public void mouseExited(MouseEvent e) {
                // 当鼠标退出组件时，设置卡片的边框为一个由实线边框和空白边框组成的复合边框
                card.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                        BorderFactory.createEmptyBorder(15, 15, 15, 15)
                ));
            }
        });


        return card;
    }
    
    /**
     * 根据描述导航到相应的详情页面
     * @param description 描述
     */
    private static void navigateToDetailPage(String description) {
        updateStatusMessage("正在打开: " + description);
        
        switch (description) {
            case "商品基础信息":
                BasicMassageInfo.showProductInfoPage();
                break;
            case "商品分类":
                ProductCategoryInfo.showCategoryInfoPage();
                break;
            case "仓库信息":
                WarehouseInfo.showWarehouseInfoPage();
                break;
            case "库存记录":
                InvenToryInfo.showInventoryInfoPage();
                break;
            case "供应商信息":
                SupplierInfo.showSupplierInfoPage();
                break;
            case "客户信息":
                CustomersInfo.showCustomersPage();
                break;
            case "销售订单信息":
                SalesInfo.showSalesInfoPage();
                break;
            case "销售发货信息":
                SalesShipmentsInfo.showSalesShipmentsPage();
                break;
            default:
                updateStatusMessage("未找到对应的页面: " + description);
                break;
        }
    }

    /**
     * 获取商品总数
     * @return 商品总数字符串
     */
    private static String getProductCount() {
        List<Products> products = ProductService.selectAllProducts();
        return String.valueOf(products.size());
    }
    
    /**
     * 获取分类总数
     * @return 分类总数字符串
     */
    private static String getCategoryCount() {
        List<ProductCategories> categories = SelectCateGory.selectAllCateGory();
        return String.valueOf(categories.size());
    }
    
    /**
     * 获取仓库总数
     * @return 仓库总数字符串
     */
    private static String getWarehouseCount() {
        try {
            List<com.xky.pojo.Warehouses> warehouses = WarehouseService.selectAllWarehouses();
            return String.valueOf(warehouses.size());
        } catch (Exception e) {
            return "0";
        }
    }
    
    /**
     * 获取库存情况
     * @return 库存情况描述
     */
    private static String getInventoryCount() {
        try {
            List<com.xky.pojo.Inventory> inventories = SelectInvenTory.selectAllInventory();
            return String.valueOf(inventories.size());
        } catch (Exception e) {
            return "0";
        }
    }

    /**
     * 查询所有的供应商总数
     * @return 供应商总数
     */
    private static String getSupplierCount() {
        List<Supplier> supplierList = SelectSupplier.selectAll();
        return String.valueOf(supplierList.size());
    }

    /**
     * 查询所有的客户
     * @return
     */
    private static String getCustomerCount() {
        List<Customers> customersList = SelectCustomers.selectAllCustomers();
        return String.valueOf(customersList.size());
    }

    /**
     * 查询所有的销售订单信息
     * @return
     */
    private static String getSalesOrderCount() {
        List<SalesOrders> salesOrders = SelectSalesOrder.selectAll();
        return String.valueOf(salesOrders.size());
    }

    /**
     *查询所有的销售发货信息
     * @return
     */
    private static String getSalesShipmentCount() {
        List<SalesShipments> salesShipments = SelectSalesShipment.selectAll();
        return String.valueOf(salesShipments.size());
    }

    /**
     * 创建商品信息面板
     * @param refreshAction 刷新操作
     * @return 商品信息面板
     */
    //Runnable refreshAction:可运行的刷新操作
    public static JPanel createProductInfoPanel(Runnable refreshAction) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部面板（标题和按钮）
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel titleLabel = new JLabel("商品基本信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        // 分割线
        JSeparator separator = new JSeparator();
        separator.setPreferredSize(new Dimension(1200, 1));
        separator.setBackground(SEPARATOR_COLOR);
        
        // 操作按钮面板
        JPanel buttonPanel = createButtonPanel(refreshAction);
        
        // 添加到顶部面板
        topPanel.add(titlePanel, BorderLayout.NORTH);
        topPanel.add(separator, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 表格
        JScrollPane scrollPane = createProductTable();
        
        // 添加到主面板
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建按钮面板
     * @param refreshAction 刷新操作
     * @return 按钮面板
     */
    private static JPanel createButtonPanel(Runnable refreshAction) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonPanel.setBackground(SECONDARY_COLOR);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // 创建按钮
        JButton addButton = createStyledButton("添加", BUTTON_COLOR);
        JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
        JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
        JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
        JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);

        // 添加事件监听器
        addButton.addActionListener(_ -> {
            new AddProduct();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        deleteButton.addActionListener(_ -> {
            new DeleteProduct();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        updateButton.addActionListener(_ -> {
            new UpdateProduct();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        queryButton.addActionListener(_ -> {
            SelectProduct selectProduct = new SelectProduct();
            selectProduct.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    // 使用getId()静态方法获取ID
                    Integer id = SelectProduct.getId();
                    if (id != null){
                        List<Products> products = ProductService.selectProductById(id);
                        if (!products.isEmpty()) {
                            
                            // 清空表格并只显示查询到的商品
                            DefaultTableModel model = (DefaultTableModel) table.getModel();
                            model.setRowCount(0);
                            updateTableData(table, products);
                            
                            // 停止自动刷新
                            if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
                                System.out.println("停止自动刷新");
                                autoRefreshTimer.stop();
                            }
                        }
                    }
                }
            });
        });

        refreshButton.addActionListener(e -> {
            System.out.println("你点击了刷新按钮");
            
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            if (refreshAction != null) {
                refreshAction.run();
                updateStatusMessage("商品数据已刷新");
            }
            
            // 重新启动自动刷新
            if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
                System.out.println("重新启动自动刷新");
                autoRefreshTimer.start();
            }
        });

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(refreshButton);

        return buttonPanel;
    }
    
    /**
     * 创建统一风格的按钮
     * @param text 按钮文本
     * @param bgColor 背景颜色
     * @return 按钮对象
     */
    private static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(100, 35));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        return button;
    }

    /**
     * 创建商品表格
     * @return 表格滚动面板
     */
    public static JScrollPane createProductTable() {
        String[] title = {"商品ID", "编码", "名称", "所属分类ID", "计量单位", "最小库存量", "是否上架", "创建时间", "更新时间"};
        DefaultTableModel model = new DefaultTableModel(title, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
        };
        
        table = new JTable(model);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        table.getTableHeader().setOpaque(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setAutoCreateRowSorter(true);
        table.setShowGrid(true);
        table.setGridColor(new Color(230, 230, 230));
        
        // 设置表格列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(60);  // 商品ID
        table.getColumnModel().getColumn(1).setPreferredWidth(80);  // 编码
        table.getColumnModel().getColumn(2).setPreferredWidth(120); // 名称
        table.getColumnModel().getColumn(3).setPreferredWidth(80);  // 所属分类ID
        table.getColumnModel().getColumn(4).setPreferredWidth(80);  // 计量单位
        table.getColumnModel().getColumn(5).setPreferredWidth(80);  // 最小库存量
        table.getColumnModel().getColumn(6).setPreferredWidth(80);  // 是否上架
        table.getColumnModel().getColumn(7).setPreferredWidth(150); // 创建时间
        table.getColumnModel().getColumn(8).setPreferredWidth(150); // 更新时间
        
        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        scrollPane.getViewport().setBackground(Color.WHITE);
        
        return scrollPane;
    }
    
    /**
     * 更新表格数据
     * @param table 表格
     * @param productsList 商品列表
     */
    public static void updateTableData(JTable table, List<Products> productsList) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        
        // 创建日期格式化器
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        for (Products product : productsList) {
            // 格式化日期时间
            String createdTime = product.getCreatedTime() != null ? product.getCreatedTime().format(formatter) : "";
            String updatedTime = product.getUpdatedTime() != null ? product.getUpdatedTime().format(formatter) : "";
            
            Object[] rowData = {
                    product.getProductId(),
                    product.getProductCode(),
                    product.getProductName(),
                    product.getCategoryId(),
                    product.getUnitOfMeasure(),
                    product.getMinStockLevel(),
                    product.getIsActive(),
                    createdTime,
                    updatedTime
            };
            model.addRow(rowData);
        }
    }

    // 添加按钮事件处理
    private static void handleAddButtonClick() {
        // 获取主窗口
        for (Frame frame : JFrame.getFrames()) {
            if (frame instanceof JFrame && frame.isVisible() && frame.getTitle().contains("商品库存管理系统")) {
                break;
            }
        }
        // 打开添加商品对话框
        new AddProduct().setVisible(true);
    }

}